package com.yjt.fresh.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.Api.BaseResultEntity;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.HttpManager;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener;
import com.yjt.fresh.R;
import com.yjt.fresh.activity.AtyGetCoupon;
import com.yjt.fresh.adpater.AdpRvAtyMyCoupon;
import com.yjt.fresh.api.ApiDeleteCoupon;
import com.yjt.fresh.api.ApiGetCoupons;
import com.yjt.fresh.base.BaseSimpleFragment;
import com.yjt.fresh.bean.BeanCoupon;
import com.yjt.fresh.constant.MyConstants;
import com.yjt.fresh.utils.PreferenceManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import static android.nfc.tech.MifareUltralight.PAGE_SIZE;

/**
 * 优惠券已经过期
 * Created by mcc on 2018/6/17.
 */

public class FrgMyCouponOverdue extends BaseSimpleFragment {
    private static final int REQUEST_CODE = 1006;
    @BindView(R.id.rv_app_aty_mycoupon_frg_overdue)
    RecyclerView mRv;
    @BindView(R.id.srlAppAtyMyCouponFrgOverdue)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.cbAppAtyMyCouponOverdueSelectAll)
    CheckBox mCbSelectAll;
    @BindView(R.id.tvAppAtyMyCouponOverdueCancel)
    TextView mTvCancel;
    @BindView(R.id.tvAppAtyMyCouponOverdueMassDelete)
    TextView mTvMassDelete;
    @BindView(R.id.tvAppAtyMyCouponOverdueToCouponCenter)
    TextView mTvToCouponCenter;
    @BindView(R.id.tvAppAtyMyCouponOverdueDelete)
    TextView mTvDelete;
    @BindView(R.id.llAppAtyMyCouponOverdueBottomToCenter)
    LinearLayout mLlBottomToCenter;
    @BindView(R.id.llAppAtyMyCouponOverdueBottomDelete)
    LinearLayout mLlBottomDelete;
    private AdpRvAtyMyCoupon mAdpMyCoupon;
    private int mNextRequestPage = 1;
    private boolean isLoadMore;

    @Override
    protected int getContentView() {
        return R.layout.app_aty_mycoupon_frg_overdue;
    }

    @Override
    protected void initView(Bundle savedInstanceState, View view) {
        ButterKnife.bind(this, view);
    }

    @Override
    protected void initEvents() {
        initRV();
        initClick();
        getData();
    }

    private void initClick() {
        mTvToCouponCenter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, AtyGetCoupon.class);
                startActivityForResult(intent,REQUEST_CODE);
            }
        });

        mTvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mAdpMyCoupon.getData().size() > 0){
                    mLlBottomToCenter.setVisibility(View.GONE);
                    mLlBottomDelete.setVisibility(View.VISIBLE);
                    mAdpMyCoupon.isShowCb(true);
                }
            }
        });
        mTvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLlBottomToCenter.setVisibility(View.VISIBLE);
                mLlBottomDelete.setVisibility(View.GONE);
                mAdpMyCoupon.isShowCb(false);
                mAdpMyCoupon.isCheck(false);
                mCbSelectAll.setChecked(false);
            }
        });

        mTvMassDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteMyCoupon();
            }
        });
        mCbSelectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mAdpMyCoupon.isCheck(isChecked);
            }
        });
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mNextRequestPage = 1;
                isLoadMore = false;
                getData();
            }
        });

        mAdpMyCoupon.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                isLoadMore = true;
                getData();
            }
        }, mRv);
    }

    HttpOnNextListener<BaseResultEntity> mDeleteCouponListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            List<BeanCoupon.ListBean> data = mAdpMyCoupon.getData();
            for (int i = data.size()-1; i >=0 ; i--) {
                if (data.get(i).isCheck()){
                    mAdpMyCoupon.remove(i);
                }
            }
            mLlBottomToCenter.setVisibility(View.VISIBLE);
            mLlBottomDelete.setVisibility(View.GONE);
            mAdpMyCoupon.isShowCb(false);
            mAdpMyCoupon.isCheck(false);
            mCbSelectAll.setChecked(false);

        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };
    private void deleteMyCoupon() {
        ApiDeleteCoupon apiDeleteCoupon  = new ApiDeleteCoupon(mDeleteCouponListener,mContext,true,false,false);
        Map<String,Object> map = new HashMap<>();
        String deleteID = "";
        List<BeanCoupon.ListBean> data = mAdpMyCoupon.getData();
        ArrayList<String> deleteIDs = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).isCheck()){
                deleteIDs.add(data.get(i).getCOUPON_ID());
            }
        }
        if (deleteIDs.size() > 0){
            for (int i = 0; i < deleteIDs.size(); i++) {
                if (i != deleteIDs.size() - 1){
                    deleteID += deleteIDs.get(i) + ",";
                }else {
                    deleteID += deleteIDs.get(i);
                }
            }
            map.put("SESSION_ID",PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
            map.put("COUPONRECEIVE_ID",deleteID);
            apiDeleteCoupon.setMap(map);
            HttpManager.getInstance().doHttpDeal(apiDeleteCoupon);
        }else {
            //TODO 优惠券删除 刷新又有的问题
            Toast.makeText(mContext, "请先选择要删除的优惠券", Toast.LENGTH_SHORT).show();
        }
    }

    HttpOnNextListener<BeanCoupon> mCouponListener = new HttpOnNextListener<BeanCoupon>() {
        @Override
        public void onNext(BeanCoupon beanCoupon) {
            mAdpMyCoupon.setEmptyView(R.layout.view_empty);
            if (isLoadMore) {
                setData(false, beanCoupon.getList());
            } else {
                setData(true, beanCoupon.getList());
                mRefreshLayout.setRefreshing(false);
            }
        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };

    private void setData(boolean isRefresh, List<BeanCoupon.ListBean> data) {
        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mAdpMyCoupon.getData().clear();
            mAdpMyCoupon.addData(data);
            mAdpMyCoupon.setEnableLoadMore(false);
        } else {
            if (size > 0) {
                mAdpMyCoupon.addData(data);
                mAdpMyCoupon.loadMoreComplete();
            }else {
                mAdpMyCoupon.loadMoreEnd(true);
            }
        }
    }

    private void getData() {
        ApiGetCoupons apiGetCoupons = new ApiGetCoupons(mCouponListener, mContext, true, false, false);
        Map<String, Object> map = new HashMap<>();
        map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        map.put("currentPage", mNextRequestPage);
        map.put("STATUS", "3");
        apiGetCoupons.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiGetCoupons);
    }

    private void initRV() {
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        mRv.setLayoutManager(manager);
        List<BeanCoupon.ListBean> list = new ArrayList<>();
        mAdpMyCoupon = new AdpRvAtyMyCoupon(R.layout.app_recycle_item_aty_mycoupon_frg, list);
        mAdpMyCoupon.setStatus(MyConstants.OVERDUE);
        mRv.setAdapter(mAdpMyCoupon);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE){
            mNextRequestPage = 1;
            isLoadMore = false;
            getData();
        }
    }
}
